package server;	

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.util.Arrays;
import client.Identifier;
import client.Information;
import security.SealedObj;
import security.Signature;
import database.DatabaseOperationsIdentifiers;
import java.util.Hashtable;

public class Authenticator {

	
	private DatabaseOperationsIdentifiers dbOpIdentifiers;
	private SealedObj sealed;
	private Signature signature;
	private Boolean accessSynchronized;
    private Hashtable<String,Integer> listIdentifiers;


	public Authenticator(DatabaseOperationsIdentifiers dbOpIdentifiers,
			SealedObj sealed, Signature signature){
		this.sealed = sealed;
		this.signature = signature;
		this.dbOpIdentifiers = dbOpIdentifiers;
		this.accessSynchronized = new Boolean(true);
        this.listIdentifiers = new Hashtable<String, Integer>();
	}


	public Information loginClient(Identifier identifier)
            throws  IOException, SQLException{
		synchronized (accessSynchronized) {
			try {

				Information information = (Information) sealed.getUnsealedObj(identifier.getSealedInfo());

				if( Arrays.equals(identifier.getSignedInfo(),signature.getSignature(information)) &&
						dbOpIdentifiers.existsIdentifierId(information.getEmail(),information.getId()) &&
                        !listIdentifiers.containsKey(information.getEmail())
                        ){

                    listIdentifiers.put(information.getEmail(),information.getId());

					return information;
				}
			}
			catch (GeneralSecurityException e){}
			catch (ClassNotFoundException e) {}

			return null;
		}
	}


	public void logoutClient(String email){
		synchronized (accessSynchronized) {
             listIdentifiers.remove(email);
    	}
	}


    public int getNumberIdentifiers(){
		synchronized (accessSynchronized) {
            return	listIdentifiers.size();
		}
	}


	public void close()
            throws SQLException{
		synchronized (accessSynchronized) {
			if(dbOpIdentifiers!=null){
				dbOpIdentifiers.close();
			}
		}		
	}


}


